home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: RANDOM NUMBER GENERATOR
- Date: 7 Jan 1996 11:42:14 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4cot56$f3d@umbc9.umbc.edu>
- References: <4cniff$11o$1@mhade.production.compuserve.com>
- NNTP-Posting-Host: f-umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Merlin Chowkwanyun <71702.1123@CompuServe.COM> wrote:
- |> Just thought you might like to know that I found this random number
- |> generator lying around in an old C++ magazine
- |>
- |> /declares a global random number generating function
- |>
- |> int random(int MaxVal)
- |> {
- |> return rand() % MaxVal;
- |> }
- |>
- |> Be sure to include the header file stdlib.h
-
- That will certainly return a random number in the range [0,MaxVal), but isn't
- the best way to do it. Here's why:
-
- 13.16: How can I get random integers in a certain range?
-
- A: The obvious way,
-
- rand() % N /* POOR */
-
- (which tries to return numbers from 0 to N-1) is poor, because
- the low-order bits of many random number generators are
- distressingly *non*-random. (See question 13.18.) A better
- method is something like
-
- (int)((double)rand() / ((double)RAND_MAX + 1) * N)
-
- If you're worried about using floating point, you could use
-
- rand() / (RAND_MAX / N + 1)
-
- Both methods obviously require knowing RAND_MAX (which ANSI
- #defines in <stdlib.h>), and assume that N is much less than
- RAND_MAX.
-
- (Note, by the way, that RAND_MAX is a *constant* telling you
- what the fixed range of the C library rand() function is. You
- cannot set RAND_MAX to some other value, and there is no way of
- requesting that rand() return numbers in some other range.)
-
- If you're starting with a random number generator which returns
- floating-point values between 0 and 1, all you have to do to get
- integers from 0 to N-1 is multiply the output of that generator
- by N.
-
- References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-